package com.joe.socket.Dao;

import com.joe.socket.Model.UserSession;
import org.springframework.stereotype.Repository;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserSessionDao {

    private final Map<String, UserSession> sessionStore = new ConcurrentHashMap<>();
    private final Map<String, String> usernameToSessionId = new ConcurrentHashMap<>();

    public void saveSession(UserSession session) {
        if (session == null || session.getSessionId() == null) {
            return;
        }
        sessionStore.put(session.getSessionId(), session);
        if (session.getUsername() != null) {
            usernameToSessionId.put(session.getUsername(), session.getSessionId());
        }
    }

    public UserSession getSessionById(String sessionId) {
        return sessionStore.get(sessionId);
    }

    public UserSession getSessionByUsername(String username) {
        String sessionId = usernameToSessionId.get(username);
        return sessionId != null ? sessionStore.get(sessionId) : null;
    }

    public void removeSession(String sessionId) {
        UserSession session = sessionStore.get(sessionId);
        if (session != null) {
            usernameToSessionId.remove(session.getUsername());
        }
        sessionStore.remove(sessionId);
    }

    public List<UserSession> getAllSessions() {
        return sessionStore.values().stream().collect(Collectors.toList());
    }

    public List<UserSession> getActiveSessions() {
        return sessionStore.values().stream()
                .filter(session -> session != null && session.isActive())
                .collect(Collectors.toList());
    }

    public int getActiveUserCount() {
        return (int) sessionStore.values().stream()
                .filter(session -> session != null && session.isActive())
                .count();
    }

    public boolean isUsernameTaken(String username) {
        UserSession session = getSessionByUsername(username);
        return session != null && session.isActive();
    }
}